import { useEffect, useCallback } from 'react';
import { useSettingsStore } from './settingsStore';
import { settingsSelectors } from './settingsSelectors';
import type { IUserPreferences, IDisplaySettings } from './settingsStore';
import type { ThemeMode } from '../../types/common/base';

/**
 * 主题管理 Hook
 * @description 提供主题相关的状态和操作方法
 */
export const useTheme = () => {
  const store = useSettingsStore();
  
  // 监听系统主题变化
  useEffect(() => {
    if (!store.followSystemTheme) return;
    
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleChange = () => {
      if (store.followSystemTheme) {
        // 触发重新计算有效主题
        store.setFollowSystemTheme(true);
      }
    };
    
    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, [store.followSystemTheme]);
  
  return {
    // 状态
    themeMode: settingsSelectors.getThemeMode(store),
    effectiveTheme: settingsSelectors.getEffectiveTheme(store),
    isDarkTheme: settingsSelectors.isDarkTheme(store),
    followSystemTheme: settingsSelectors.isFollowingSystemTheme(store),
    customPrimaryColor: settingsSelectors.getCustomPrimaryColor(store),
    isUsingCustomColor: settingsSelectors.isUsingCustomColor(store),
    themeConfig: settingsSelectors.getThemeConfig(store),
    
    // 操作
    setThemeMode: store.setThemeMode,
    toggleTheme: store.toggleTheme,
    setFollowSystemTheme: store.setFollowSystemTheme,
    setCustomPrimaryColor: store.setCustomPrimaryColor,
    detectSystemTheme: store.detectSystemTheme
  };
};

/**
 * 用户偏好设置 Hook
 * @description 提供用户偏好设置相关的状态和操作方法
 */
export const useUserPreferences = () => {
  const store = useSettingsStore();
  
  const updatePreference = useCallback(<K extends keyof IUserPreferences>(
    key: K,
    value: IUserPreferences[K]
  ) => {
    store.updateUserPreferences({ [key]: value });
  }, [store]);
  
  return {
    // 状态
    preferences: settingsSelectors.getUserPreferences(store),
    language: settingsSelectors.getLanguage(store),
    timeFormat: settingsSelectors.getTimeFormat(store),
    dateFormat: settingsSelectors.getDateFormat(store),
    weekStartsOn: settingsSelectors.getWeekStartsOn(store),
    defaultCourseDuration: settingsSelectors.getDefaultCourseDuration(store),
    showWeekends: settingsSelectors.shouldShowWeekends(store),
    soundNotifications: settingsSelectors.isSoundNotificationEnabled(store),
    desktopNotifications: settingsSelectors.isDesktopNotificationEnabled(store),
    autoSaveInterval: settingsSelectors.getAutoSaveInterval(store),
    backupFrequency: settingsSelectors.getBackupFrequency(store),
    localizationConfig: settingsSelectors.getLocalizationConfig(store),
    notificationConfig: settingsSelectors.getNotificationConfig(store),
    
    // 操作
    updatePreferences: store.updateUserPreferences,
    updatePreference,
    resetPreferences: store.resetUserPreferences
  };
};

/**
 * 显示设置 Hook
 * @description 提供显示设置相关的状态和操作方法
 */
export const useDisplaySettings = () => {
  const store = useSettingsStore();
  
  const updateSetting = useCallback(<K extends keyof IDisplaySettings>(
    key: K,
    value: IDisplaySettings[K]
  ) => {
    store.updateDisplaySettings({ [key]: value });
  }, [store]);
  
  return {
    // 状态
    settings: settingsSelectors.getDisplaySettings(store),
    defaultScheduleView: settingsSelectors.getDefaultScheduleView(store),
    showCourseColors: settingsSelectors.shouldShowCourseColors(store),
    showTeacherInfo: settingsSelectors.shouldShowTeacherInfo(store),
    showLocationInfo: settingsSelectors.shouldShowLocationInfo(store),
    courseCardSize: settingsSelectors.getCourseCardSize(store),
    enableAnimations: settingsSelectors.isAnimationEnabled(store),
    sidebarCollapsed: settingsSelectors.isSidebarCollapsed(store),
    tablePageSize: settingsSelectors.getTablePageSize(store),
    scheduleDisplayConfig: settingsSelectors.getScheduleDisplayConfig(store),
    performanceConfig: settingsSelectors.getPerformanceConfig(store),
    
    // 操作
    updateSettings: store.updateDisplaySettings,
    updateSetting,
    resetSettings: store.resetDisplaySettings
  };
};

/**
 * 设置面板 Hook
 * @description 提供设置面板相关的状态和操作方法
 */
export const useSettingsPanel = () => {
  const store = useSettingsStore();
  
  return {
    // 状态
    visible: settingsSelectors.isSettingsPanelVisible(store),
    activeTab: settingsSelectors.getActiveSettingsTab(store),
    resetConfirmVisible: settingsSelectors.isResetConfirmVisible(store),
    
    // 操作
    show: store.showSettings,
    hide: store.hideSettings,
    toggle: store.toggleSettings,
    setActiveTab: store.setActiveSettingsTab,
    showResetDialog: store.showResetDialog,
    hideResetDialog: store.hideResetDialog
  };
};

/**
 * 设置数据管理 Hook
 * @description 提供设置数据导入导出相关的操作方法
 */
export const useSettingsData = () => {
  const store = useSettingsStore();
  
  const exportToFile = useCallback(async (filename?: string) => {
    try {
      const settingsJson = await store.exportSettings();
      const blob = new Blob([settingsJson], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = filename || `course-schedule-settings-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('导出设置失败:', error);
      throw error;
    }
  }, [store]);
  
  const importFromFile = useCallback((file: File): Promise<void> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = async (e) => {
        try {
          const content = e.target?.result as string;
          await store.importSettings(content);
          resolve();
        } catch (error) {
          reject(error);
        }
      };
      
      reader.onerror = () => {
        reject(new Error('文件读取失败'));
      };
      
      reader.readAsText(file);
    });
  }, [store]);
  
  return {
    // 状态
    isLoading: settingsSelectors.isLoading(store),
    error: settingsSelectors.getError(store),
    lastUpdated: settingsSelectors.getLastUpdated(store),
    settingsSummary: settingsSelectors.getSettingsSummary(store),
    hasModifiedSettings: settingsSelectors.hasModifiedSettings(store),
    
    // 操作
    exportSettings: store.exportSettings,
    importSettings: store.importSettings,
    exportToFile,
    importFromFile,
    resetAllSettings: store.resetAllSettings
  };
};

/**
 * 完整设置管理 Hook
 * @description 提供所有设置相关的状态和操作方法的综合接口
 */
export const useSettings = () => {
  const theme = useTheme();
  const preferences = useUserPreferences();
  const display = useDisplaySettings();
  const panel = useSettingsPanel();
  const data = useSettingsData();
  
  return {
    // 主题相关
    theme,
    
    // 用户偏好
    preferences,
    
    // 显示设置
    display,
    
    // 面板控制
    panel,
    
    // 数据管理
    data,
    
    // 综合状态
    snapshot: settingsSelectors.getSettingsSnapshot(useSettingsStore()),
    
    // 快捷操作
    quickActions: {
      toggleTheme: theme.toggleTheme,
      toggleSidebar: () => display.updateSetting('sidebarCollapsed', !display.sidebarCollapsed),
      toggleAnimations: () => display.updateSetting('enableAnimations', !display.enableAnimations),
      toggleWeekends: () => preferences.updatePreference('showWeekends', !preferences.showWeekends),
      toggleSoundNotifications: () => preferences.updatePreference('enableSoundNotifications', !preferences.soundNotifications),
      toggleDesktopNotifications: () => preferences.updatePreference('enableDesktopNotifications', !preferences.desktopNotifications)
    }
  };
};

/**
 * 设置初始化 Hook
 * @description 用于应用启动时初始化设置相关功能
 */
export const useSettingsInitialization = () => {
  const { theme, preferences } = useSettings();
  
  useEffect(() => {
    // 初始化主题
    const effectiveTheme = theme.effectiveTheme;
    document.documentElement.setAttribute('data-theme', effectiveTheme);
    
    // 设置自定义主题色
    if (theme.isUsingCustomColor) {
      document.documentElement.style.setProperty('--primary-color', theme.customPrimaryColor);
    }
  }, [theme.effectiveTheme, theme.customPrimaryColor, theme.isUsingCustomColor]);
  
  useEffect(() => {
    // 初始化语言设置
    document.documentElement.setAttribute('lang', preferences.language);
  }, [preferences.language]);
  
  useEffect(() => {
    // 请求桌面通知权限
    if (preferences.desktopNotifications && 'Notification' in window) {
      if (Notification.permission === 'default') {
        Notification.requestPermission();
      }
    }
  }, [preferences.desktopNotifications]);
  
  return {
    initialized: true
  };
};